package com.ellen.mac.chatdemo.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.avos.avoscloud.im.v2.AVIMConversation;
import com.avos.avoscloud.im.v2.AVIMException;
import com.avos.avoscloud.im.v2.AVIMMessage;
import com.avos.avoscloud.im.v2.callback.AVIMMessagesQueryCallback;
import com.avos.avoscloud.im.v2.messages.AVIMTextMessage;
import com.ellen.mac.chatdemo.R;
import com.ellen.mac.chatdemo.adpter.ImageAdapter;
import com.ellen.mac.chatdemo.adpter.TextAdapter;
import com.ellen.mac.chatdemo.model.DataMP3Bean;
import com.ellen.mac.chatdemo.model.DataPhotoBean;
import com.ellen.mac.chatdemo.model.DataTextBean;
import com.ellen.mac.chatdemo.model.TeacherData;
import com.ellen.mac.chatdemo.utils.LogUtils;
import com.ellen.mac.chatdemo.utils.NotificationUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;


import java.util.ArrayList;
import java.util.List;

/**
 * Created by j on 2017/12/13.
 */

public class ChatRoomFragment extends Fragment  {

    protected AVIMConversation imConversation;

    protected LinearLayoutManager textLayoutManager;
    protected LinearLayoutManager imageLayoutManager;
    protected List<DataMP3Bean> mp3List;
    protected List<DataPhotoBean> photoList;
    protected List<DataTextBean> textList;

    protected RecyclerView imageRecyclerView,textRecyclerView;
    protected ImageAdapter imageAdapter;
    protected TextAdapter textAdapter;

    protected Button up,next;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.new_chat_layout, container, false);
        imageRecyclerView = view.findViewById(R.id.image_recycler);
        textRecyclerView = view.findViewById(R.id.text_recycler);

        //设置布局管理器
        textLayoutManager = new LinearLayoutManager(getActivity());
        imageLayoutManager = new LinearLayoutManager(getActivity());
        textLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        imageLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        imageRecyclerView.setLayoutManager(textLayoutManager);
        textRecyclerView.setLayoutManager(imageLayoutManager);
        getAdpter();
        textAdapter.resetRecycledViewPoolSize(textRecyclerView);
        imageAdapter.resetRecycledViewPoolSize(imageRecyclerView);
        textRecyclerView.setAdapter(textAdapter);
        imageRecyclerView.setAdapter(imageAdapter);
        return view;
    }

    protected void getAdpter() {
        mp3List = new ArrayList<>();
        photoList = new ArrayList<>();
        textList = new ArrayList<>();
        imageAdapter = new ImageAdapter(R.layout.item_new_image,photoList,getActivity());
        textAdapter = new TextAdapter(R.layout.item_new_text,textList,getActivity());

    }

    //拉取事件
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        fetchMessages();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (null != imConversation) {
            NotificationUtils.addTag(imConversation.getConversationId());
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (null != imConversation) {
            NotificationUtils.removeTag(imConversation.getConversationId());
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    public void setConversation(final AVIMConversation conversation) {
        imConversation = conversation;
        fetchMessages();
    }
    /**
     * 拉取消息，必须加入 conversation 后才能拉取消息
     */
    private void fetchMessages() {
        if(imConversation!= null){
            LogUtils.v(imConversation.toString());
            imConversation.queryMessages(100,new AVIMMessagesQueryCallback() {
                @Override
                public void done(List<AVIMMessage> messageList, AVIMException e) {
                    if (filterException(e)) {
                        putData(messageList);
                    }
                }
            });
        }else{
            LogUtils.e("null---");
        }
    }

    public void putData(List<AVIMMessage> messageList){
        textList.clear();
        photoList.clear();
        mp3List.clear();
        for(int i=0;i<messageList.size();i++){
            AVIMMessage message = messageList.get(i);
            if (message instanceof AVIMTextMessage) {
                TeacherData data = null;
                AVIMTextMessage textMessage = (AVIMTextMessage) message;
                try {
                    data = new Gson().fromJson(textMessage.getText(), TeacherData.class);
                }catch (JsonSyntaxException exception){
                    LogUtils.logException(exception);
                }finally {
                    if(data != null){
                        long time = textMessage.getTimestamp();
                        DataTextBean text = new DataTextBean();
                        if(!data.getText().trim().isEmpty()){
                            text.setOutTime(time);
                            text.setContent(data.getText());
                            LogUtils.i("-----"+data.getText()+"-----");
                            textList.add(text);
                        }
                        for(DataMP3Bean mp3: data.getAudio()){
                            mp3.setOutTime(time);
                            mp3List.add(mp3);
                        }
                        for (DataPhotoBean photo:data.getImage()){
                            photo.setOutTime(time);
                            photoList.add(photo);
                        }

                    }
                }
            }
        }
        imageAdapter.setNewData(photoList);
        textAdapter.setNewData(textList);
        imageAdapter.notifyDataSetChanged();
        textAdapter.notifyDataSetChanged();
        //todo 装载mp3数据
        clearUnreadConut();


    }
    private boolean filterException(Exception e) {
        if (null != e) {
            LogUtils.logException(e);
            Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        return (null == e);
    }
    private void clearUnreadConut() {
        if (imConversation.getUnreadMessagesCount() > 0) {
            imConversation.read();
        }
    }
}
